// oneOf
export const oneOf = (target, list) => {
  for (let i = 0; i < list.length; i++) {
    if (target === list[i]) {
      return true;
    }
  }
  return false;
};

// 函数节流 (一定时间调用一次，缩减执行频率)
export const throttle = (fn, time) => {
  let last = 0;
  return function() {
    let now = +new Date();
    if (now - last > time) {
      fn && fn.apply(this, arguments);
      last = now;
    }
  };
};

/**
 * 函数防抖 (规定时间只会调用一次)
 * @param {*} time 时间
 * @param {*} fn 方法
 */
export const debounce = (fn, time) => {
  let timer = null;
  return function() {
    let that = this;
    let args = arguments;
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }
    timer = setTimeout(function() {
      fn && fn.apply(that, args);
    }, time);
  };
};

// deepCopy
export const deepCopy = (obj, cache = []) => {
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }
  const hit = find(cache, c => c.original === obj);
  if (hit) {
    return hit.copy;
  }

  const copy = Array.isArray(obj) ? [] : {};
  cache.push({
    original: obj,
    copy
  });

  Object.keys(obj).forEach(key => {
    copy[key] = deepCopy(obj[key], cache);
  });
  return copy;
};

// 扁平化数组
export const flatten = (array, children = 'children', arrList = []) => {
  for (const item of array) {
    arrList.push(item);
    if (item[children] && item[children].length) {
      flatten(item[children], children, arrList);
    }
  }
  return arrList;
};

/**
 * 格式化日期
 * @param  {[type]} str [description]
 * @return {[type]} fmt   [description] yyyy-MM-dd hh:mm:ss
 */
export const DateFormat = (str, fmt) => {
  let o = {
    'M+': str.getMonth() + 1,
    'd+': str.getDate(),
    'h+': str.getHours(),
    'm+': str.getMinutes(),
    's+': str.getSeconds(),
    'q+': Math.floor((str.getMonth() + 3) / 3),
    S: str.getMilliseconds()
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (str.getFullYear() + '').substr(4 - RegExp.$1.length));
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
    }
  }
  return fmt;
};
export const toHHmmss = date => {
  var time;
  var hours = parseInt((date % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = parseInt((date % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = parseInt((date % (1000 * 60)) / 1000);
  time =
    (hours < 10 ? '0' + hours : hours) +
    ':' +
    (minutes < 10 ? '0' + minutes : minutes) +
    ':' +
    (seconds < 10 ? '0' + seconds : seconds);
  return time;
};

export const formattedDateTime = timestamp => {
  // 使用 Date 对象的构造函数将毫秒时间戳转换为日期对象
  const date = new Date(timestamp);

  // 使用 Date 对象的方法获取年、月、日、时、分、秒等信息
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1，并补零
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  // 返回格式化后的日期时间字符串
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 绑定事件
export const addEvent = (el, type, fn) => {
  if (el.attachEvent) {
    el.attachEvent(`on${type}`, fn);
  } else if (el.addEventListener) {
    el.addEventListener(type, fn, false);
  } else {
    el[`on${type}`] = null;
  }
};

// 移除事件
export const removeEvent = (el, type, fn) => {
  if (el.datachEvent) {
    el.datachEvent(`on${type}`, fn);
  } else if (el.removeEventListener) {
    el.removeEventListener(type, fn, false);
  } else {
    el[`on${type}`] = null;
  }
};

//初始化单位树数据
export const _initDepartmentTreeData = (list, parentId) => {
  if (parentId == undefined) parentId = '';
  var zNodes = [];
  for (var i = 0, l = list.length; i < l; i++) {
    var item = list[i];
    if (item.parentId == parentId) {
      var obj = {
        nodeId: item.departmentId + '_' + i,
        departmentID: item.departmentId,
        name: item.departmentName,
        nodeStatus: 'department',
        parentId: item.parentId,
        leaf: item.leaf
      };
      obj.children = _initDepartmentTreeData(list, item.departmentId);
      if (!obj.children.length) delete obj.children;
      zNodes.push(obj);
    }
  }
  return zNodes;
};

//将树结构转数组
export const transformTreeToArray = (treeData, parentNode) => {
  var nodes = [];
  if (parentNode == undefined || parentNode == null || parentNode == '') {
    treeData.forEach(item => {
      item.parentId = '';
      item.parentName = '';
      item.level = 1;
      nodes.push(item);
      nodes.push.apply(nodes, transformTreeToArray(treeData, item));
    });
  } else {
    parentNode.children &&
      parentNode.children.forEach(item => {
        item.parentId = parentNode.departmentID;
        item.parentName = parentNode.name;
        item.level = parentNode.level + 1;
        nodes.push(item);
        nodes.push.apply(nodes, transformTreeToArray(treeData, item));
      });
  }
  return nodes;
};
// let msg = { command: 'logout', data: {} }; 数据体格式
export const winOpenerPostMsg = msg => {
  if (window.opener) {
    window.opener.postMessage(JSON.stringify(msg), '*');
  }
};

/**unix时间转换 */
export const switchUnixTime = time => {
  var unixTimestamp = new Date(time * 1000);
  // var commonTime = unixTimestamp.toLocaleString();
  var commonTime = DateFormat(unixTimestamp,'yyyy-MM-dd hh:mm:ss');
  return unixTimestamp;
};
